<template>
  <div class="app-container">
    <!--条件搜索表单-->
    <el-row :gutter="20">
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item>
          <el-input v-model="searchObj.name" placeholder="商品名称" />
        </el-form-item>
        <el-form-item>
          <el-input-number v-model="searchObj.priceStart" placeholder="最低价格" controls-position="right" />
        </el-form-item>
        <el-form-item>
          <el-input-number v-model="searchObj.priceEnd" placeholder="最高价格" controls-position="right" />
        </el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="getAll()">查询</el-button>
        <el-button icon="el-icon-refresh" @click="reset()">清空</el-button>
      </el-form>
    </el-row>
    <el-row :gutter="20" style="margin-top: 10px">
      <el-button type="primary" icon="el-icon-plus" @click="openEdit(null)">新增</el-button>
      <el-button type="danger" icon="el-icon-delete" :disabled="ids.length < 1" @click="batchDelete">
        批量删除
      </el-button>
    </el-row>

    <!-- banner列表 :data="list"表示遍历list数组 stripe条纹 -->
    <el-table
      v-loading="loading"
      element-loading-text="正在努力加载数据中..."
      :data="page.list"
      :border="false"
      stripe
      style="width: 100%; margin: 15px 0px"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" fixed="left" width="55" />
      <el-table-column type="index" fixed="left" width="80" label="序号" />
      <el-table-column prop="name" fixed="left" label="商品名称" min-width="100" sortable show-overflow-tooltip />
      <el-table-column prop="imageUrl" fixed="left" label="商品图片" min-width="100" sortable show-overflow-tooltip>
        <template v-slot="scope">
          <el-image
            :src="scope.row.imageUrl"
            :preview-src-list="[scope.row.imageUrl]"
            style="width: 60px; height: 60px"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="unit" label="商品单位" show-overflow-tooltip />
      <el-table-column prop="price" label="商品单价" min-width="100" sortable show-overflow-tooltip>
        <template v-slot="scope">￥{{ scope.row.price }} </template>
      </el-table-column>
      <el-table-column prop="stock" label="商品库存" min-width="100" sortable show-overflow-tooltip />
      <el-table-column prop="popularity" label="商品人气" min-width="100" sortable />
      <el-table-column prop="description" label="商品描述" min-width="100" sortable show-overflow-tooltip />
      <el-table-column prop="createTime" label="创建时间" min-width="100" sortable show-overflow-tooltip />

      <!-- 操作 -->
      <el-table-column label="操作" width="220" fixed="right" align="center">
        <template slot-scope="scope">
          <el-link type="primary" icon="el-icon-view" @click="openDetail(scope.row)">详情</el-link>
          <el-divider direction="vertical" />
          <el-link type="success" icon="el-icon-edit" @click="openEdit(scope.row)">编辑</el-link>
          <el-divider direction="vertical" />
          <el-link type="danger" icon="el-icon-remove" @click="remove(scope.row.id)">删除</el-link>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页导航栏 -->
    <div>
      <el-pagination
        :background="true"
        :current-page="pIndex"
        :page-size="pSize"
        :total="page.total"
        :page-sizes="[1, 3, 6, 9, 12, 15, 18]"
        layout="total, sizes, ->, prev, pager, next, jumper"
        @current-change="getAll"
        @size-change="handleSizeChange"
      />
    </div>

    <!-- 表单 -->
    <el-dialog :title="dialogTitle" :visible.sync="visible" width="40%" @close="close('productForm')">
      <el-form ref="productForm" :rules="rules" :model="product" label-width="100px">
        <el-row :gutter="35">
          <el-col>
            <el-form-item label="商品图片">
              <el-upload
                class="image-upload"
                :action="uploadAction"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="product.imageUrl" :src="product.imageUrl" class="image" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="商品ID" prop="id" :hidden="true">
              <el-input v-model="product.id" />
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="商品名称" prop="name">
              <el-input v-model="product.name" placeholder="请输入商品名称" />
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="商品单位" prop="unit">
              <el-input v-model="product.unit" placeholder="请输入商品单位" />
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="商品价格" prop="price">
              <el-input-number
                v-model="product.price"
                placeholder="请输入商品价格"
                :min="0.01"
                :max="99999"
                controls-position="right"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="商品库存" prop="stock">
              <el-input-number
                v-model="product.stock"
                placeholder="请输入商品库存"
                :min="1"
                :max="99999"
                controls-position="right"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="12">
            <el-form-item label="商品描述" prop="description">
              <el-input
                type="textarea"
                v-model="product.description"
                placeholder="请输入商品描述"
                :autosize="{ minRows: 3 }"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="close('productForm')">取 消</el-button>
        <el-button type="primary" @click="save('productForm')">确 定</el-button>
      </div>
    </el-dialog>

    <Detail :productId="productId" :visible="showDetail" @update:visible="showDetail = !showDetail" />
  </div>
</template>

<script>
// 引入api接口定义的js文件
import productApi from '@/api/product'
import Detail from './detail/index.vue'

export default {
  components: { Detail },
  props: {
    categoryId: { type: Number, required: true, default: 0 }
  },
  data() {
    // 定义变量和初始值
    return {
      // 查询条件
      searchObj: {},

      // 列表相关
      loading: false, // 加载状态
      pIndex: 1, // 当前页
      pSize: 6, // 每页显示记录数
      page: [], // 列表
      ids: [], // 选中的列ID

      // 表单相关
      dialogTitle: '',
      visible: false, // 是否显示表单
      product: {
        id: undefined,
        categoryId: undefined,
        name: '',
        imageUrl: '',
        unit: '',
        price: 0.01,
        stock: 1,
        description: ''
      },
      // 验证规则
      rules: {
        name: [{ required: true, message: '商品名称不能为空', trigger: 'blur' }],
        unit: [{ required: true, message: '商品单位不能为空', trigger: 'blur' }]
      },

      uploadAction: 'http://localhost',

      // 商品详情
      showDetail: false,
      productId: undefined
    }
  },
  created() {
    this.uploadAction = process.env.VUE_APP_BASE_API + '/file/upload'
  },
  watch: {
    categoryId(val) {
      this.searchObj.categoryId = val
      this.product.categoryId = val
      this.getAll()
    }
  },
  methods: {
    // 加载列表数据
    getAll(current = 1) {
      this.loading = true
      this.pIndex = current
      productApi
        .getPage(this.pIndex, this.pSize, this.searchObj)
        .then((response) => {
          this.page = response.data
        })
        .finally(() => {
          this.loading = false
        })
    },

    // 行内筛选
    filterHandler(value, row, column) {
      const property = column['property']
      return row[property] === value
    },

    // 改变页码
    handleSizeChange(pageSize) {
      this.pSize = pageSize
      // 重新调用数据加载方法 --> 方法中已经加入的查询参数
      this.getAll()
    },

    // 删除商品信息
    remove(id) {
      this.$confirm('此操作将永久删除商品信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          productApi.remove(id).then((resp) => {
            this.$message.success('删除成功！')
            this.getAll()
          })
        })
        .catch(() => {
          this.$message.info('已取消删除！')
        })
    },

    // 复选框选中
    handleSelectionChange(r) {
      // 得到选中的id
      this.ids = r.map((v) => v.id)
    },

    // 打开表单页面
    openEdit(row) {
      this.dialogTitle = '新增商品'
      this.visible = true
      this.product.imageUrl = ''

      if (row != null) {
        this.dialogTitle = '编辑商品'
        productApi.getById(row.id).then((res) => {
          const data = res.data
          Object.assign(this.product, data)
        })
      }
    },

    // 关闭表单
    close(form) {
      this.visible = false
      this.$refs[form].resetFields()
    },

    // 保存
    save(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          console.log(this.product)
          const apiCall = this.product.id ? productApi.update(this.product) : productApi.save(this.product)
          apiCall.then(() => {
            this.$message.success('操作成功')
            this.close(form)
            this.getAll()
          })
        }
      })
    },

    // 批量删除
    batchDelete() {
      if (this.ids.length > 0) {
        this.$confirm('此操作将永久删除商品信息,是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          // 确定执行then方法
          .then(() => {
            productApi.batchRemove(this.ids).then((resp) => {
              this.$message.success('删除成功！')
              this.getAll()
            })
          })
          .catch(() => {
            this.$message.info('已取消删除！')
          })
      } else {
        this.$message.warning('至少选择一条数据!')
      }
    },

    // 重置
    reset() {
      this.searchObj = {
        categoryId: this.product.categoryId
      }
      this.getAll()
    },

    // 图片上传成功
    handleAvatarSuccess(res) {
      if (res.code === 200) {
        this.product.imageUrl = res.data
      }
    },

    // 图片上传前
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 3

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG|PNG|JPEG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 3MB!')
      }

      return isJPG && isLt2M
    },

    // 打开详情
    openDetail(row) {
      this.showDetail = true
      this.productId = row.id
    }
  }
}
</script>

<style>
.image-upload .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.image {
  width: 100px;
  height: 100px;
  display: block;
}
</style>
